#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdbool.h>

#include "operate.h"


#define OP_MUTEX op_mutex
static pthread_mutex_t op_mutex = PTHREAD_MUTEX_INITIALIZER;

static bool is_cmd(const char *arg, const char *command);

/*根据指令类型调用不同的函数*/
int handleToServ(Client *p_cli, int fd_serv){
    //handleCommand(p_cli->cmd.cmd_arg, &p_cli->cmd.type);
    switch(p_cli->cmd.type){
    case CMD_FALSE:
        printf("指令错误，请重新输入\n");
        break;
    case CMD_LS:        //ls指令
        printf("命令\"ls\"处理中...\n");
        op_ls(p_cli, fd_serv);
        break;      
    case CMD_CD:        //cd指令
        printf("命令\"cd\"处理中...\n");
        op_cd(p_cli, fd_serv);
        break;
    case CMD_PUTS:      //puts指令
        printf("命令\"puts\"处理中...\n");
        op_puts(p_cli, fd_serv);
        break;
    case CMD_GETS:      //gets指令
        printf("命令\"gets\"处理中...\n");
        op_gets(p_cli, fd_serv);
        break;
    case CMD_MKDIR:      //mkdir指令
        printf("命令\"mkdir\"处理中...\n");
        op_mkdir(p_cli, fd_serv);
        break;
    case CMD_RM:        //rm指令
        printf("命令\"rm\"处理中...\n");
        op_rm(p_cli, fd_serv);
        break;
    case CMD_PWD:       //pwd指令
        op_pwd(p_cli, fd_serv);
        break;
    case CMD_LOGIN:     //login指令
        op_login(p_cli, fd_serv);
        break;
    case CMD_REGISTER:  //register指令
        op_register(p_cli, fd_serv);
        break;
    default:
        puts("指令错误，请重新输入\n");
        break;
    }
    return 0;
}

/*处理指令参数中的 /.. */
int handleCommand(char *arg, CMD_TYPE *p_type){
    //todo
    //char tmp[OP_BUF_SIZE] = {0};
    //strcpy(tmp, arg);
    //strcpy(arg,"");

    //char *token = strtok(tmp," ");
    //while(!strcmp(token, " ")){
    //    token = strtok(NULL, " ");
    //}
    //puts(token);
    
    if(is_cmd(arg, "ls")){
    //if(!strncmp("ls", arg, strlen(arg))){
        *p_type = CMD_LS;
    }else if(is_cmd(arg, "cd")){
        *p_type = CMD_CD;
    }else if(is_cmd(arg, "puts")){
        *p_type = CMD_PUTS;
    }else if(is_cmd(arg, "gets")){
        *p_type = CMD_GETS;
    }else if(is_cmd(arg, "rm")){
        *p_type = CMD_RM;
    }else if(is_cmd(arg, "mkdir")){
        *p_type = CMD_MKDIR;
    }else if(is_cmd(arg, "pwd")){
        *p_type = CMD_PWD;
    }else if(is_cmd(arg, "login")){
        *p_type = CMD_LOGIN;
    }else if(is_cmd(arg, "register")){
        *p_type = CMD_REGISTER;
    }else{
        *p_type = CMD_FALSE;
        return -1;
    }

    //while(!strcmp(token, " ")){
    //    //todo 处理空格
    //    printf("puts:%s\n", token);
    //    token = strtok(NULL, " ");
    //}
    //strcpy(arg, token);
    return 0;
}


static bool is_cmd(const char *arg, const char *command){
    return (!strncmp(command, arg, strlen(command)) && !strncmp(command, arg, strlen(arg)));
}
